import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, DatePicker, Radio, message, ConfigProvider } from 'antd';
import PropTypes from 'prop-types';
import { QuickForm } from 'vv-frontend-components';
import { groupBy } from 'lodash';
// import { history } from 'umi';
import moment from 'moment';
import { FormContainer, SelectForm, TreeSelectForm } from '@/components/UserForm';
import {
    getCandicationInfo
    // getOfferDetail
} from '@/services/myRecruit/offerDetail';
import PersonInfo from '@/components/PersonInfo';
import { dictionaryList } from '@/services/dictionary';
import { getOptionData, getRadioOptionData } from '@/pages/Flow/Mine/ApplyPage/utils';
// import { getCompanyTree } from '@/services/components/userform';
import request from '@/utils/request';

const { Option } = Select;

const formItemLayout = {
    labelCol: {
        md: { span: 5 },
        xs: { span: 24 },
        sm: { span: 24 }
    },
    wrapperCol: {
        md: { span: 19 },
        xs: { span: 24 },
        sm: { span: 24 }
    }
};

const QuickEntry = ({ form, onOk, candidateCode, visible, ...rest }) => {
    // const user = localStorage.getItem('user')
    //     ? JSON.parse(localStorage.getItem('user'))
    //     : {};
    const { getFieldDecorator } = form;
    const [detail, setDetail] = useState({});
    // const [companyList, setCompanyList] = useState([]);
    // const [departmentList, setDepartmentList] = useState([]);
    // const [postList, setPostList] = useState([]);
    // const [roleList, setRoleList] = useState([]);
    const [agreeList, setAgreeList] = useState([]);
    const [sexList, setSexList] = useState([]);
    const [companyId, setCompanyId] = useState('');
    const [confirmLoading, setConfirmLoading] = useState(false);
    const handleOk = async () => {
        form.validateFieldsAndScroll(async err => {
            if (!err) {
                const { timeOfEntry, prefix, ...values } = form.getFieldsValue();
                setConfirmLoading(true);
                const response = await request('/api/oa/v1/offer/quickentry', {
                    method: 'POST',
                    data: {
                        ...values,
                        areaCode: prefix,
                        candidateCode: detail.candidateCode,
                        employeeName: detail.talentName,
                        talentCode: detail.talentCode,
                        timeOfEntry: timeOfEntry ? moment(timeOfEntry).format('YYYY-MM-DD') : ''
                    }
                });

                if (response.code === 10000) {
                    message.success('操作成功！');
                    setConfirmLoading(false);
                    onOk();
                } else {
                    message.error(response.msg);
                    setConfirmLoading(false);
                }
            }
        });
    };
    const companyChange = value => {
        setCompanyId(value);
        form.setFieldsValue({
            departmentId: null,
            postId: undefined,
            roles: []
        });
    };
    useEffect(() => {
        const fetchList = async () => {
            const response = await getCandicationInfo(candidateCode);

            if (response.code === 10000) {
                setDetail(response.data);
            }
        };
        const fetchDicts = async codes => {
            const response = await dictionaryList({
                codes
            });
            if (response.code === 10000) {
                const group = groupBy(response.data, 'code');
                setSexList(
                    getRadioOptionData(group.sexType, {
                        key: 'dictValue',
                        label: 'dictName'
                    })
                );
                setAgreeList(
                    getOptionData(group.agreeType, {
                        key: 'dictValue',
                        label: 'dictName'
                    })
                );
            }
        };
        if (visible && candidateCode) {
            fetchDicts(['sexType', 'agreeType']);
            fetchList();
        }
    }, [candidateCode, visible]);
    const getSexName = key => {
        if (key === '1') {
            return 'man';
        }
        if (key === '2') {
            return 'woman';
        }
        return '';
    };
    return (
        <Modal
            title="快速入职"
            width={900}
            id="quickEntry"
            onOk={handleOk}
            visible={visible}
            confirmLoading={confirmLoading}
            destroyOnClose
            {...rest}
        >
            <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                <PersonInfo
                    name={`${detail.talentName || ''}-${detail.entryPostName || ''}`}
                    status={detail.offerStateName || ''}
                    sex={getSexName(detail.talentSex)}
                    color="green"
                    style={{
                        marginBottom: 10
                    }}
                />
                <Form layout="horizontal" {...formItemLayout}>
                    <FormContainer>
                        <Form.Item label="用户名">
                            {getFieldDecorator('userName', {
                                rules: [
                                    {
                                        required: true,
                                        message: '用户名不能为空'
                                    },
                                    {
                                        pattern: /^[a-zA-Z,_-\s]{1,}$/,
                                        message: '只限定输入英文字符'
                                    },
                                    {
                                        min: 2,
                                        max: 50,
                                        message: '用户名字数范围:2到50个字符'
                                    }
                                ]
                            })(<Input placeholder="2-50个英文字符" />)}
                        </Form.Item>
                        <Form.Item label="企业邮箱">
                            {getFieldDecorator('email', {
                                rules: [
                                    {
                                        type: 'email',
                                        message: '请输入正确格式的邮箱！'
                                    },
                                    {
                                        required: true,
                                        message: '请输入邮箱！'
                                    }
                                ]
                            })(<Input />)}
                        </Form.Item>
                        <Form.Item label="手机号">
                            {getFieldDecorator('mobile', {
                                initialValue: detail.talentPhone || '',
                                rules: [
                                    {
                                        required: true,
                                        validator(rule, value, callback) {
                                            const regex = /^\d{7,11}$/;
                                            if (!value) {
                                                callback('手机号不能为空');
                                            } else if (!regex.test(value)) {
                                                callback('只能输入7-11位数字');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <Input
                                    addonBefore={getFieldDecorator('prefix', {
                                        initialValue: detail.companyId === 101 ? '86' : '65'
                                    })(
                                        <Select style={{ width: 70 }}>
                                            <Option value="86">+86</Option>
                                            <Option value="65">+65</Option>
                                        </Select>
                                    )}
                                />
                            )}
                        </Form.Item>
                        {/* 根据规则自动生成员工工号 */}
                        {/* <Form.Item label="员工工号">
                            {getFieldDecorator('userNo', {
                                rules: [
                                    {
                                        required: true,
                                        message: '员工工号不能为空'
                                    },
                                    {
                                        pattern: /^[a-zA-Z0-9]+$/,
                                        message: '只能为数字或英文字母'
                                    },
                                    {
                                        min: 2,
                                        max: 15,
                                        message: '2-15个字符'
                                    }
                                ]
                            })(<Input placeholder="2-15个字符" />)}
                        </Form.Item> */}
                        <Form.Item label="入职时间">
                            {getFieldDecorator('timeOfEntry', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入入职时间'
                                    }
                                ]
                            })(<DatePicker style={{ width: '100%' }} />)}
                        </Form.Item>
                        <Form.Item label="所属公司">
                            {getFieldDecorator('companyId', {
                                initialValue: detail.companyId || '',
                                rules: [
                                    {
                                        required: true,
                                        message: '所属公司不能为空'
                                    }
                                ]
                            })(
                                <TreeSelectForm
                                    params={{
                                        companyId: detail.companyId || companyId
                                    }}
                                    requireParam={['companyId']}
                                    getData={params =>
                                        request('/api/org/v1/functional/list', {
                                            params
                                        }).then(res => {
                                            if (res && res.code === 10000 && res.data) {
                                                return res.data || [];
                                            }
                                            return [];
                                        })
                                    }
                                    fieldsName={{
                                        value: 'id',
                                        title: 'companyName'
                                    }}
                                    onChange={companyChange}
                                    Props={{
                                        placeholder: '请所属选择公司',
                                        showArrow: true
                                    }}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="部门">
                            {getFieldDecorator('departmentId', {
                                initialValue: undefined
                            })(
                                <TreeSelectForm
                                    params={{
                                        companyId: form.getFieldValue('companyId') || companyId
                                    }}
                                    defaultExpand="department"
                                    requireParam={['companyId']}
                                    getData={params =>
                                        request('/api/org/v1/functional/list', {
                                            params
                                        }).then(res => {
                                            if (res && res.code === 10000 && res.data) {
                                                return res.data || [];
                                            }
                                            return [];
                                        })
                                    }
                                    fieldsName={{
                                        value: 'id',
                                        title: 'departmentName'
                                    }}
                                    Props={{
                                        placeholder: '请选择部门',
                                        showArrow: true
                                    }}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="职位">
                            {getFieldDecorator('postId', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '职位不能为空'
                                    }
                                ]
                            })(
                                <SelectForm
                                    params={{
                                        companyId: form.getFieldValue('companyId') || companyId
                                    }}
                                    requireParam={['companyId']}
                                    getData={params =>
                                        request(`/api/oa/v1/post/getpostlistbycompanyid/${params.companyId}`).then(
                                            res => {
                                                if (res && res.code === 10000 && res.data) {
                                                    return res.data || [];
                                                }
                                                return [];
                                            }
                                        )
                                    }
                                    fieldsName={{
                                        selectValue: 'id',
                                        selectTitle: 'postName'
                                    }}
                                    selectProps={{
                                        placeholder: '请选择职位'
                                    }}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="角色">
                            {getFieldDecorator('roles', {
                                initialValue: [],
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择角色'
                                    }
                                ]
                            })(
                                <SelectForm
                                    params={{
                                        companyId: form.getFieldValue('companyId') || companyId
                                    }}
                                    requireParam={['companyId']}
                                    getData={params =>
                                        request(`/api/oa/v1/role/getallrole/${params.companyId}`).then(res => {
                                            if (res && res.code === 10000 && res.data) {
                                                return res.data || [];
                                            }
                                            return [];
                                        })
                                    }
                                    fieldsName={{
                                        selectValue: 'id',
                                        selectTitle: 'roleName'
                                    }}
                                    selectProps={{
                                        showArrow: false,
                                        mode: 'multiple',
                                        placeholder: '请选择角色',
                                        dropdownRender: menu => (
                                            <div>
                                                {menu}
                                                {/*                                           <Button
                                                htmlType="button"
                                                style={{ width: '100%' }}
                                                // see:https://github.com/ant-design/ant-design/issues/13504
                                                onMouseDown={() => {
                                                    history.push(
                                                        '/setting/role/add'
                                                    );
                                                }}
                                            >
                                                马上添加新角色
                                            </Button> */}
                                            </div>
                                        )
                                    }}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="最高学历">
                            {getFieldDecorator('highestDegree', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择最高学历'
                                    }
                                ]
                            })(
                                <Select>
                                    {agreeList.map(item => (
                                        <Option value={item.key} key={item.key}>
                                            {item.label}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item label="性别">
                            {getFieldDecorator('sex', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择性别'
                                    }
                                ]
                            })(<Radio.Group options={sexList} />)}
                        </Form.Item>
                    </FormContainer>
                </Form>
            </ConfigProvider>
        </Modal>
    );
};

QuickForm.propTypes = {
    candidateCode: PropTypes.string.isRequired
};

export default Form.create()(QuickEntry);
